package behaviorlearning;

import java.util.LinkedList;
import java.util.List;

import util.XMLWriter;
import base.WargusGameState;
import base.WargusMap;
import base.WargusPlayer;



public class Case {
	int m_ID;
	List<String> m_goals;
	/*WargusMap m_map;
	List<WargusPlayer> m_players;
	*/
	WargusGameState m_state;
	CaseSolution m_solution;
	
	public Case(int ID, List<String> goals, WargusMap map,
			List<WargusPlayer> players,WargusAction action) {
		m_ID = ID;
		m_goals = new LinkedList<String>();
		for(String g:goals) m_goals.add(g);
		LinkedList<WargusPlayer> m_players = new LinkedList<WargusPlayer>();
		for(WargusPlayer p:players) m_players.add(new WargusPlayer(p));
		m_solution = new CaseSolution();
		m_solution.m_type = CaseSolution.BASICOPERATOR;
		m_solution.m_action = action;
		{
			List<WargusPlayer> opponents = new LinkedList<WargusPlayer>();
			WargusPlayer self = null;
			for(WargusPlayer p:players) {
				if (p.getID()==action.m_playerID) self = p;
										     else opponents.add(p);
			}
			m_state = new WargusGameState(map, opponents, self); // is it okay for both to reference same game state?
			m_solution.m_action.setContext(m_state);			
		}		
	}
	
	public Case(Case c) {
		m_ID = c.m_ID;
		m_goals = new LinkedList<String>();
		for(String g:c.m_goals) m_goals.add(g);
		/*m_map = new WargusMap(c.m_map);
		m_players = new LinkedList<WargusPlayer>();
		for(WargusPlayer p:c.m_players) m_players.add(new WargusPlayer(p));
		*/
		m_solution = new CaseSolution(c.m_solution);
		m_state = new WargusGameState(c.m_state);
	}
	
	public void writeXML(XMLWriter w) throws Exception {
		w.tag("case");		
		{
			// Goals are already XML strings.
			for (String g : m_goals) {
				w.rawXML(g);
			}
			
			m_state.writeXML(w);
			
			w.tag("solution");			
			{
				m_solution.writeXML(w);
			}
			w.tag("/solution");
		}
		w.tag("/case");
	}
	
	public void writeBehaviorXML(XMLWriter w, String ID_prefix) throws Exception {
		w.tag("behavior id=\"" + ID_prefix +  "-" + m_ID + "\"");
		{
			// Goals are already XML strings.
			for (String g : m_goals) {
				w.rawXML(g);
			}
		
			w.tag("plan");
			{
				m_solution.writeXML(w);
			}			
			w.tag("/plan");
		}
		w.tag("/behavior");
	}	
	
	public void writeEpisodeXML(XMLWriter w, String ID_prefix) throws Exception {
		w.tag("episode");
		{
			w.tag("behavior", ID_prefix +  "-" + m_ID);
				
			m_state.writeXML(w);

			w.tag("outcome");
			{
				w.tag("player", 0);
				w.tag("success", 1.0);
		    	//w.tag("time", 0);
			}
			w.tag("/outcome");
		}
		w.tag("/episode");
	}		
	
}
